/*
 * @author: liubing
 * @Date: 2020-12-12 21:09:51
 * @desc: 
 */

 ///
 // 读取shader
function loadShader(gl, type, source) {
    if (type == gl.VERTEX_SHADER) {
        console.log("loadShder -> vertex_shader");
    }else if (type == gl.FRAGMENT_SHADER) {
        console.log("loadShder -> fragment_shader");
    }
    const shader = gl.createShader(type);
    gl.shaderSource(shader,source);
    gl.compileShader(shader);

    if(!gl.getShaderParameter(shader,gl.COMPILE_STATUS)){
        console.error("An error occurred compiling the shaders:");
        gl.deleteShader(shader);
        return null;
    }
    return shader;
}

//  初始化shader
function initShaderProgram(gl,vertSource,fragSource){
    const vertexShader = loadShader(gl,gl.VERTEX_SHADER,vertSource);
    const fragShader = loadShader(gl,gl.FRAGMENT_SHADER,fragSource);

    const shaderProgram = gl.createProgram();
    gl.attachShader(shaderProgram,vertexShader);
    gl.attachShader(shaderProgram,fragShader);
    gl.linkProgram(shaderProgram);

    // failed
    if(!gl.getProgramParameter(shaderProgram,gl.LINK_STATUS)){
        console.error("Unable to initialize the shader program: " + gl.getProgramInfoLog(shaderProgram));
        return null;
    }
    return shaderProgram;
}

// loadTexture
function loadTexture(gl, url,callback) {

    const texture = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_2D, texture);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([0, 0, 255, 255]))

    const image = new Image();
    image.src = url;
    image.onload = function () {
        gl.bindTexture(gl.TEXTURE_2D, texture);
        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
        if (isPowerOf2(image.width) && isPowerOf2(image.height)) {
            gl.generateMipmap(gl.TEXTURE_2D);
        } else {
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
        }
        if(callback) {
            callback(texture);
        }
    }
    return texture;
}
function isPowerOf2(value) {
    return (value & (value - 1)) == 0;
}